﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Camping_Project_WEB.Models;

namespace Camping_Project_WEB.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        public Camping_BDD _bdd = new Camping_BDD();
        public ASPNETBDD _asp = new ASPNETBDD();
        public Guid uniqueID;

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Le nom d'utilisateur ou mot de passe fourni est incorrect.");
                }
            }

            // Si nous sommes arrivés là, quelque chose a échoué, réafficher le formulaire
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Tentative d'inscription de l'utilisateur
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("InfosClient", "Account");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // Si nous sommes arrivés là, quelque chose a échoué, réafficher le formulaire
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "Le mot de passe actuel est incorrect ou le nouveau mot de passe n'est pas valide.");
                }
            }

            // Si nous sommes arrivés là, quelque chose a échoué, réafficher le formulaire
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


        // **************************************
        // URL: /Account/InfosClient
        // **************************************

        public ActionResult InfosClient()
        {
            //ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InfosClient(InfosClient model)
        {
            //GUID = uniqueIdentifier type
            

            //Verification si le modele est rempli correctement
            if (ModelState.IsValid)
            {
                //Recherche de l'ID correspondant a la personne connectée sur la session
                var query =         from user in _asp.aspnet_Users
                                    where user.UserName == User.Identity.Name
                                    select user.UserId;


                //Recupération de l'id unique
                uniqueID = query.Single();

                try
                {
                    //User.Identity.Name;
                    Client cl = new Client
                    {
                        Nom = model.nomClient,
                        Prenom = model.prenomClient,
                        DateNaissance = DateTime.Parse(model.dateNaissanceClient),
                        Adresse = model.adresseClient,
                        CodePostal = model.cpClient,
                        Ville = model.villeClient,
                        Pays = model.paysClient,
                        Telephone = model.telClient,
                        Email = model.emailClient,
                        IDuser = uniqueID
                    };

                    _bdd.Client.AddObject(cl);
                    _bdd.SaveChanges();
                    return RedirectToAction("ModifSuccess");
                }
                catch
                {
                    return View();
                }
            }

            // Si nous sommes arrivés là, quelque chose a échoué, réafficher le formulaire
            //ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }


        public ActionResult ModifSuccess()
        {
            return View();
        }


        public ActionResult VoirInfosClient()
        {

            //Recherche des informations du client dans la BDD
            
            //Recherche de l'ID correspondant a la personne connectée sur la session
            var query = from user in _asp.aspnet_Users
                        where user.UserName == User.Identity.Name
                        select user.UserId;

            //Recupération de l'id unique
            uniqueID = query.Single();
            
            //Selection des informations clients
            var queryClient =   (from client in _bdd.Client
                                where client.IDuser == uniqueID
                                select client);

            //Selection des anciennes réservations
            var queryReservOld = from reserv in _bdd.Reservation
                              where reserv.IDClient == queryClient.FirstOrDefault().IDClient && reserv.PayementEffectue == true
                              select reserv;
            //Selection des Nouvelles réservations (En cours)
            var queryReservNew = from reserv in _bdd.Reservation
                                 where reserv.IDClient == queryClient.FirstOrDefault().IDClient && reserv.PayementEffectue == false
                                 select reserv;

           // Client cli = (Client)queryClient;

            ViewData["ReservOld"] = queryReservOld;
            ViewData["ReservNew"] = queryReservNew;
            ViewData.Model = (Client)queryClient.Single();
            

            return View();
        }

        /*
        public ActionResult VoirInfosClient(InfosClient model)
        {


            
            //Recherche des informations du client dans la BDD

            //Recherche de l'ID correspondant a la personne connectée sur la session
            var query = from user in _asp.aspnet_Users
                        where user.UserName == User.Identity.Name
                        select user.UserId;

            //Recupération de l'id unique

            foreach (var r in query)
            {
                uniqueID = r;
            }


            var queryClient =   from client in _bdd.Client
                                where client.IDuser == uniqueID
                                select client;

            Client cli = (Client)queryClient;

            model.nomClient = cli.Nom;
            model.prenomClient = cli.Prenom;
            model.dateNaissanceClient = cli.DateNaissance.ToString();
            model.adresseClient = cli.Adresse;
            model.cpClient = cli.CodePostal;
            model.villeClient = cli.CodePostal;
            model.paysClient = cli.Pays;
            model.telClient = cli.Telephone;
            model.emailClient = cli.Email;

            return View();

        }
        */


    }
}
